<template>
  <div class="profile-page">
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">医生个人中心</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/portal' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>医生服务</el-breadcrumb-item>
          <el-breadcrumb-item>个人中心</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <div class="container main-content">
      <el-row :gutter="20" v-loading="loading">
        <!-- 左侧个人信息卡片 -->
        <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
          <div class="user-card">
            <div class="user-avatar">
              <el-avatar :size="100" :src="userAvatar">
                {{ doctorInfo.name?.charAt(0) || userStore.name?.charAt(0) || userStore.username?.charAt(0) || '医' }}
              </el-avatar>
            </div>
            <h2 class="user-name">{{ doctorInfo.name || userStore.name || userStore.username }}</h2>
            <p class="user-role">{{ doctorInfo.title || '医生' }}</p>
            <div class="doctor-info">
              <p><el-icon><OfficeBuilding /></el-icon> {{ doctorInfo.department || '暂无科室' }}</p>
            </div>
            <div class="user-stats">
              <div class="stat-item">
                <div class="stat-value">{{ doctorStats.appointments || 0 }}</div>
                <div class="stat-label">今日预约</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ doctorStats.patients || 0 }}</div>
                <div class="stat-label">接诊患者</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ doctorStats.consultations || 0 }}</div>
                <div class="stat-label">今日就诊</div>
              </div>
            </div>
          </div>
          
          <!-- 快速链接 -->
          <div class="quick-links">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>快速访问</span>
                </div>
              </template>
              <div class="link-list">
                <div class="link-item" @click="navigateTo('/portal/doctor/workstation')">
                  <el-icon><FirstAidKit /></el-icon>
                  <span>医生工作站</span>
                </div>
                <div class="link-item" @click="navigateTo('/portal/doctor/workstation')">
                  <el-icon><Calendar /></el-icon>
                  <span>我的预约</span>
                </div>
                <div class="link-item" @click="navigateTo('/portal/doctor/workstation')">
                  <el-icon><User /></el-icon>
                  <span>患者管理</span>
                </div>
                <div class="link-item" @click="navigateTo('/portal/doctor/workstation')">
                  <el-icon><Document /></el-icon>
                  <span>就诊记录</span>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
        
        <!-- 右侧信息和设置 -->
        <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="18">
          <el-tabs>
            <!-- 个人资料标签页 -->
            <el-tab-pane label="个人资料">
              <el-card class="info-card">
                <template #header>
                  <div class="card-header">
                    <span>基本信息</span>
                    <el-button type="primary" @click="editMode = !editMode">
                      {{ editMode ? '取消编辑' : '编辑信息' }}
                    </el-button>
                  </div>
                </template>
                
                <el-form 
                  :model="doctorForm" 
                  :rules="doctorRules" 
                  ref="doctorFormRef"
                  label-width="120px"
                  :disabled="!editMode"
                >
                  <el-form-item label="医生ID" prop="doctorId">
                    <el-input v-model="doctorForm.doctorId" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="doctorForm.name"></el-input>
                  </el-form-item>
                  <el-form-item label="性别" prop="gender">
                    <el-select v-model="doctorForm.gender" placeholder="请选择">
                      <el-option label="男" value="男"></el-option>
                      <el-option label="女" value="女"></el-option>
                      <el-option label="其他" value="其他"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="医生职称" prop="title">
                    <el-select v-model="doctorForm.title" placeholder="请选择">
                      <el-option label="主任医师" value="主任医师"></el-option>
                      <el-option label="副主任医师" value="副主任医师"></el-option>
                      <el-option label="主治医师" value="主治医师"></el-option>
                      <el-option label="住院医师" value="住院医师"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="所属科室" prop="department">
                    <el-input v-model="doctorForm.department"></el-input>
                  </el-form-item>
                  <el-form-item label="专业特长" prop="specialty">
                    <el-input type="textarea" v-model="doctorForm.specialty"></el-input>
                  </el-form-item>
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="doctorForm.contactInfo.phone"></el-input>
                  </el-form-item>
                  <el-form-item label="电子邮箱" prop="email">
                    <el-input v-model="doctorForm.contactInfo.email"></el-input>
                  </el-form-item>
                  <el-form-item v-if="editMode">
                    <el-button type="primary" @click="updateDoctorInfo">保存信息</el-button>
                    <el-button @click="resetForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>
            
            <!-- 安全设置标签页 -->
            <el-tab-pane label="安全设置">
              <el-card class="info-card">
                <template #header>
                  <div class="card-header">
                    <span>修改密码</span>
                  </div>
                </template>
                
                <el-form 
                  :model="passwordForm" 
                  :rules="passwordRules" 
                  ref="passwordFormRef"
                  label-width="120px"
                >
                  <el-form-item label="当前密码" prop="oldPassword">
                    <el-input 
                      v-model="passwordForm.oldPassword" 
                      type="password" 
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input 
                      v-model="passwordForm.newPassword" 
                      type="password" 
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input 
                      v-model="passwordForm.confirmPassword" 
                      type="password" 
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="changePassword">修改密码</el-button>
                    <el-button @click="resetPasswordForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>
            
            <!-- 履历信息标签页 -->
            <el-tab-pane label="专业履历">
              <el-card class="info-card">
                <template #header>
                  <div class="card-header">
                    <span>专业履历</span>
                    <el-button type="primary" @click="editResumeMode = !editResumeMode">
                      {{ editResumeMode ? '取消编辑' : '编辑履历' }}
                    </el-button>
                  </div>
                </template>
                
                <el-form 
                  :model="resumeForm" 
                  ref="resumeFormRef"
                  label-width="120px"
                  :disabled="!editResumeMode"
                >
                  <el-form-item label="医生简介" prop="biography">
                    <el-input type="textarea" v-model="resumeForm.biography" :rows="4"></el-input>
                  </el-form-item>
                  <el-form-item label="教育经历" prop="education">
                    <el-input type="textarea" v-model="resumeForm.education" :rows="4" placeholder="每行一条教育经历"></el-input>
                    <div class="form-help-text">请输入您的教育经历，如"2010-2014 某大学医学院 临床医学"，每行一条</div>
                  </el-form-item>
                  <el-form-item label="执业资格" prop="certifications">
                    <el-input type="textarea" v-model="resumeForm.certifications" :rows="4" placeholder="每行一条资格证书"></el-input>
                    <div class="form-help-text">请输入您的资格证书，如"执业医师资格证"，每行一条</div>
                  </el-form-item>
                  <el-form-item v-if="editResumeMode">
                    <el-button type="primary" @click="updateResume">保存履历</el-button>
                    <el-button @click="resetResumeForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { doctorAPI, authAPI, statisticsAPI, departmentAPI } from '@/utils/api'
import { FirstAidKit, Calendar, Document, User, OfficeBuilding } from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const editMode = ref(false)
const editResumeMode = ref(false)
const doctorFormRef = ref(null)
const passwordFormRef = ref(null)
const resumeFormRef = ref(null)

// 用户头像
const userAvatar = computed(() => {
  return userStore.avatar || ''
})

// 统计数据
const doctorStats = reactive({
  appointments: 0,
  patients: 0,
  consultations: 0
})

// 医生信息
const doctorInfo = reactive({
  id: '',
  name: '',
  title: '',
  department: '',
  departmentId: '',
  specialty: '',
  scheduleDays: [],
  contactInfo: {
    phone: '',
    email: '',
    office: ''
  }
})

// 医生表单数据
const doctorForm = reactive({
  doctorId: '',
  name: '',
  gender: '',
  title: '',
  department: '',
  departmentId: '',
  specialty: '',
  scheduleDays: [],
  contactInfo: {
    phone: '',
    email: '',
    office: ''
  }
})

// 用户表单数据（基本账号信息）
const userForm = reactive({
  username: '',
  email: ''
})

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 履历表单数据
const resumeForm = reactive({
  biography: '',
  education: '',
  certifications: ''
})

// 表单验证规则
const doctorRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请选择职称', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请输入所属科室', trigger: 'blur' }
  ]
}

// 密码验证规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不少于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取医生信息
const getDoctorInfo = async () => {
  try {
    loading.value = true
    
    // 输出当前状态
    console.log('==== getDoctorInfo 开始 ====')
    
    // 从store中获取用户信息
    const userId = userStore.userInfo?.id || userStore.userInfo?._id
    
    console.log('当前用户ID:', userId)
    console.log('完整的userStore:', userStore.$state)
    console.log('userStore.userInfo:', userStore.userInfo)
    
    if (!userId) {
      console.error('获取用户ID失败')
      ElMessage.warning('获取用户信息失败，请重新登录')
      return
    }

    console.log('准备调用API获取医生信息，userId:', userId)
    
    // 通过用户ID获取医生信息
    console.log('调用 doctorAPI.getDoctorByUserId 开始')
    const res = await doctorAPI.getDoctorByUserId(userId)
    console.log('API调用结果:', res)
    
    if (res.success && res.data) {
      // 更新医生信息
      const data = res.data
      console.log('获取到的医生信息详细数据:', data)
      
      console.log('医生姓名 (data.name):', data.name)
      console.log('用户姓名 (userStore.name):', userStore.name)
      
      // 如果有departmentId，获取科室名称
      let departmentName = '未分配'
      let departmentId = ''
      if (data.departmentId) {
        try {
          console.log('尝试获取科室信息:', data.departmentId)
          departmentId = data.departmentId
          const deptRes = await departmentAPI.getDepartment(data.departmentId)
          if (deptRes.success && deptRes.data) {
            departmentName = deptRes.data.name || '未分配'
            console.log('获取到的科室名称:', departmentName)
          }
        } catch (deptError) {
          console.error('获取科室信息失败:', deptError)
        }
      }
      
      Object.assign(doctorInfo, {
        id: data._id || data.id,
        name: data.name,
        title: data.title || '医师',
        department: departmentName,
        departmentId: departmentId,
        specialty: data.specialty || (data.specialties && data.specialties.join(', ')) || '',
        contactInfo: {
          phone: data.contactInfo?.phone || '',
          email: data.contactInfo?.email || '',
          office: data.contactInfo?.office || ''
        }
      })
      
      console.log('更新后的doctorInfo:', doctorInfo)
      
      // 填充表单数据
      Object.assign(doctorForm, {
        doctorId: data.staffId || data._id || data.id,
        name: data.name,
        gender: data.gender || '',
        title: data.title || '',
        department: departmentName,
        departmentId: departmentId,
        specialty: data.specialty || (data.specialties && data.specialties.join(', ')) || '',
        contactInfo: {
          phone: data.contactInfo?.phone || '',
          email: data.contactInfo?.email || '',
          office: data.contactInfo?.office || ''
        }
      })
      
      console.log('更新后的doctorForm:', doctorForm)
      
      // 基本用户信息
      userForm.username = userStore.username || ''
      userForm.email = doctorInfo.contactInfo.email
      
      console.log('更新后的userForm:', userForm)
      
      // 获取履历信息和证书信息
      resumeForm.biography = data.biography || '';
      
      // 处理教育经历 - 如果是数组，转为文本
      if (data.education && Array.isArray(data.education)) {
        resumeForm.education = data.education.join('\n');
      } else {
        resumeForm.education = '';
      }
      
      // 处理资格证书 - 如果是数组，转为文本
      if (data.certifications && Array.isArray(data.certifications)) {
        resumeForm.certifications = data.certifications.join('\n');
      } else {
        resumeForm.certifications = '';
      }
      
      console.log('更新后的履历表单:', resumeForm);
      
      // 获取统计数据
      loadDoctorStats()
    } else {
      // 如果API没有返回医生信息，使用默认值
      console.warn('API未返回有效的医生信息')
      ElMessage.warning('无法获取医生信息，将使用基本用户信息')
      doctorInfo.name = userStore.name || userStore.username
      doctorForm.name = doctorInfo.name
      userForm.username = userStore.username || ''
      userForm.email = userStore.userInfo?.email || ''
      
      console.log('使用默认值后的信息:')
      console.log('doctorInfo:', doctorInfo)
      console.log('doctorForm:', doctorForm)
      console.log('userForm:', userForm)
    }
    
    console.log('==== getDoctorInfo 完成 ====')
  } catch (error) {
    console.error('获取医生信息失败:', error)
    ElMessage.error('获取医生信息失败')
  } finally {
    loading.value = false
  }
}

// 加载医生统计数据
const loadDoctorStats = async () => {
  try {
    // 从API获取统计数据
    if (!doctorInfo.id) {
      throw new Error('医生ID不存在，无法获取统计数据')
    }
    
    // 使用统计API获取医生统计数据
    const res = await statisticsAPI.getDoctorStats({ doctorId: doctorInfo.id })
    
    if (res.success && res.data) {
      Object.assign(doctorStats, {
        appointments: res.data.todayAppointments || 0,
        patients: res.data.totalPatients || 0,
        consultations: res.data.todayConsultations || 0
      })
    } else {
      // 使用默认值
      doctorStats.appointments = 0
      doctorStats.patients = 0
      doctorStats.consultations = 0
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 使用默认值
    doctorStats.appointments = 0
    doctorStats.patients = 0
    doctorStats.consultations = 0
  }
}

// 更新医生信息
const updateDoctorInfo = async () => {
  try {
    await doctorFormRef.value.validate()
    
    loading.value = true
    
    // 构建更新数据
    const updateData = {
      name: doctorForm.name,
      gender: doctorForm.gender,
      title: doctorForm.title,
      specialties: doctorForm.specialty ? doctorForm.specialty.split(',').map(item => item.trim()) : []
    }
    
    // 使用保存的departmentId
    if (doctorForm.departmentId) {
      updateData.departmentId = doctorForm.departmentId
      console.log('使用departmentId更新:', doctorForm.departmentId)
    }
    
    // 特殊处理contactInfo，确保为嵌套对象格式
    if (doctorForm.contactInfo) {
      updateData.contactInfo = {
        phone: doctorForm.contactInfo.phone || '',
        email: doctorForm.contactInfo.email || '',
        office: doctorForm.contactInfo.office || ''
      }
    }
    
    console.log('更新医生数据:', JSON.stringify(updateData, null, 2))
    
    // 调用API更新医生信息
    const res = await doctorAPI.updateDoctor(doctorInfo.id, updateData)
    
    console.log('更新医生响应:', JSON.stringify(res, null, 2))
    
    if (res.success) {
      ElMessage.success('医生信息更新成功')
      
      // 重新获取最新的医生信息，确保页面显示是最新的
      await getDoctorInfo()
      
      // 退出编辑模式
      editMode.value = false
      
      // 同时更新用户基本信息
      const userUpdateData = {
        name: doctorForm.name,
        email: userForm.email
      }
      
      await authAPI.updateUserInfo(userUpdateData)
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新医生信息失败:', error)
    ElMessage.error('更新医生信息失败')
  } finally {
    loading.value = false
  }
}

// 更新履历信息
const updateResume = async () => {
  try {
    await resumeFormRef.value.validate()
    
    loading.value = true
    
    // 处理教育经历和资格证书格式（从文本转为数组）
    const educationArray = resumeForm.education
      ? resumeForm.education.split('\n').filter(item => item.trim() !== '')
      : []
    
    const certificationsArray = resumeForm.certifications
      ? resumeForm.certifications.split('\n').filter(item => item.trim() !== '')
      : []
    
    // 将履历数据包装到更新对象中
    const updateData = {
      biography: resumeForm.biography,
      education: educationArray,
      certifications: certificationsArray
    }
    
    // 调用更新医生信息API
    const res = await doctorAPI.updateDoctor(doctorInfo.id, updateData)
    
    if (res.success) {
      ElMessage.success('履历信息更新成功')
      
      // 退出编辑模式
      editResumeMode.value = false
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新履历信息失败:', error)
    ElMessage.error('更新履历信息失败')
  } finally {
    loading.value = false
  }
}

// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    loading.value = true
    
    // 调用API修改密码
    const res = await authAPI.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (res.success) {
      ElMessage.success('密码修改成功')
      resetPasswordForm()
    } else {
      ElMessage.error(res.message || '密码修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  doctorFormRef.value.resetFields()
  
  // 恢复原始数据
  Object.assign(doctorForm, {
    doctorId: doctorInfo.id,
    name: doctorInfo.name,
    gender: doctorInfo.gender,
    title: doctorInfo.title,
    department: doctorInfo.department,
    departmentId: doctorInfo.departmentId,
    specialty: doctorInfo.specialty,
    scheduleDays: doctorInfo.scheduleDays,
    contactInfo: { ...doctorInfo.contactInfo }
  })
  
  userForm.email = doctorInfo.contactInfo.email || userStore.userInfo?.email || ''
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value.resetFields()
}

// 重置履历表单
const resetResumeForm = () => {
  resumeFormRef.value.resetFields()
}

// 导航到指定页面
const navigateTo = (path) => {
  router.push(path)
}

// 组件挂载时
onMounted(() => {
  // 检查用户是否登录和角色是否为医生
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/portal/login')
    return
  }
  
  if (userStore.userRole !== 'doctor') {
    ElMessage.warning('只有医生可以访问此页面')
    router.push('/portal')
    return
  }
  
  // 输出当前用户信息
  console.log('==== 组件挂载时用户信息 ====')
  console.log('userStore.userInfo:', userStore.userInfo)
  console.log('userStore.name:', userStore.name)
  console.log('userStore.username:', userStore.username)
  console.log('userStore.userRole:', userStore.userRole)
  console.log('==== 组件挂载完成 ====')
  
  // 获取医生信息
  getDoctorInfo()
})
</script>

<style scoped>
.profile-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background-color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px;
}

.main-content {
  margin-bottom: 40px;
}

.user-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px 20px;
  text-align: center;
  margin-bottom: 20px;
}

.user-avatar {
  margin-bottom: 15px;
}

.user-name {
  font-size: 20px;
  font-weight: 500;
  margin: 0 0 5px;
}

.user-role {
  color: #409EFF;
  font-size: 16px;
  margin: 0 0 15px;
}

.doctor-info {
  margin: 15px 0;
  text-align: left;
}

.doctor-info p {
  margin: 8px 0;
  display: flex;
  align-items: center;
}

.doctor-info .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin: 20px 0 10px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.quick-links {
  margin-bottom: 20px;
}

.link-list {
  display: flex;
  flex-direction: column;
}

.link-item {
  display: flex;
  align-items: center;
  padding: 15px 10px;
  cursor: pointer;
  transition: all 0.3s;
  border-bottom: 1px solid #f5f5f5;
}

.link-item:last-child {
  border-bottom: none;
}

.link-item:hover {
  background-color: #f0f9ff;
  color: #409EFF;
}

.link-item .el-icon {
  font-size: 18px;
  margin-right: 10px;
  color: #409EFF;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-help-text {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  line-height: 1.4;
}

.mt-20 {
  margin-top: 20px;
}

@media (max-width: 768px) {
  .user-card {
    margin-bottom: 20px;
  }
}
</style> 